<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getBrands">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--
		列表
		name
		englishName
		firstLetter
		description
		product_type_id
		logo
		-->
		<el-table :data="brands" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="80" sortable>
			</el-table-column>
			<el-table-column prop="englishName" label="英文名称" width="150">
			</el-table-column>
			<el-table-column prop="firstLetter" label="首字母" width="100" sortable>
			</el-table-column>
			<el-table-column prop="description" label="描述" width="120">
			</el-table-column>
			<el-table-column prop="productType.name" label="商品类型" width="150">
			</el-table-column>
			<el-table-column prop="logo" label="图标" width="120">
				<template scope="scope">
					<img :src="'http://172.16.2.128'+scope.row.logo" width="50"/>
				</template>
			</el-table-column>
			<el-table-column label="操作" min-width="150">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
				<el-form-item label="姓名" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="性别">
					<el-radio-group v-model="editForm.sex">
						<el-radio class="radio" :label="1">男</el-radio>
						<el-radio class="radio" :label="0">女</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="editForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="生日">
					<el-date-picker type="date" placeholder="选择日期" v-model="editForm.birth"></el-date-picker>
				</el-form-item>
				<el-form-item label="地址">
					<el-input type="textarea" v-model="editForm.addr"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面-->
		<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false" size="tiny">
			<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="addForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="英文名" prop="englishName">
					<el-input v-model="addForm.englishName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="类型" prop="productTypeId">
					<!--<el-input v-model="addForm.productTypeId" ></el-input>-->
					<el-cascader style="width: 100%"
							:options="options"
							v-model="addForm.productTypeId" :show-all-levels="false"
							:props="props">
					</el-cascader>
				</el-form-item>
				<el-form-item label="logo">
					<el-upload
							class="upload-demo"
							action="http://localhost:1299/services/common/fastdfs"
							:file-list="addForm.logoList"
							list-type="picture"
							:on-success="logoUploadSuccess"
							:before-upload="handleBeforeUpload"
							:on-remove="handleLogoRemove">
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item label="描述">
					<el-input type="textarea" v-model="addForm.description"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
                props:{
                    value:"id",
					label:"name",
                    children:"children"
				},
			    options:[],
				filters: {
					keyword: ''
				},
				brands: [],
				total: 0,
				page: 1,
				pageSize:10,
				listLoading: false,
				sels: [],//列表选中行

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
					id: 0,
					name: '',
					sex: -1,
					age: 0,
					birth: '',
					addr: ''
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				//添加表单验证规则
				addFormRules: {
					name: [
						{ required: true, message: '请输入名称', trigger: 'blur' }
					],
                    englishName: [
                        { required: true, message: '请输入英文名称', trigger: 'blur' }
                    ],
                    productTypeId: [
                        { type:'array',required: true, message: '请选择商品类型', trigger: 'blur' }
                    ]
				},
				//新增界面数据
				addForm: {
					name: '',
					englishName:'',
					productTypeId:[],
                    logoList:[],
					description:''
				}

			}
		},
		methods: {
            handleLogoRemove(file, fileList){
                //file 删除的文件
				//调用删除文件的接口
				let file_id = file.response.restObj
				this.$http.delete("/common/fastdfs?file_id="+file_id)
					.then(res=>{
					    let {success,message,restObj} = res.data;
					    if(success){
                            //fileList 删除后的文件列表
                            this.addForm.logoList = fileList;
						}else{
                            this.$message({
                                message:message,
                                type:"error"
                            })
						}
					})
			},
		    //图片上传之前的回调
            handleBeforeUpload(file){
                if(this.addForm.logoList.length>0){
                    this.$message({
						message:"只能上传一张图片!",
						type:"warning"
					})
                    return false;
				}
			},
		    //图片上传成功的回调
            logoUploadSuccess(response, file, fileList){
                //fileList = [{response:{success:true,restObj:''}},file,file]
                this.addForm.logoList = fileList;
                console.log(response)
			},
		    loadOptions(){
				this.$http.get("/product/productType/loadTree")
					.then(res=>{
					    this.options = res.data;
					})
			},
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getBrands();
			},
			//获取品牌列表
			getBrands() {
			    //封装查询条件（请求参数）
				let para = {
					page: this.page,
					rows:this.pageSize,
					keyword:this.filters.keyword
				};
				this.listLoading = true;
				this.$http.post("/product/brand/json",para)
					.then(res=>{
                        this.listLoading = false;
					    let pageList = res.data;
					    this.brands = pageList.rows;
					    this.total = pageList.total;
					})
				/*getUserListPage(para).then((res) => {
					this.total = res.data.total;
					this.brands = res.data.brands;
					this.listLoading = false;
					//NProgress.done();
				});*/
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					this.$http.delete("/product/brand/delete/"+row.id)
						.then(res=>{
						    let {message,success,restObj} = res.data;
                            this.listLoading = false;
						    if(success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.getBrands();
							}else{
                                this.$message({
                                    message:message ,
                                    type: 'error'
                                });
							}
						})


					/*let para = { id: row.id };
					removeUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getBrands();
					});*/
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				//清空表单
				this.addForm = {
                    name: '',
                    englishName:'',
                    productTypeId:[],
                    logoList:[],
                    description:''
                };
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.editForm);
							para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
							editUser(para).then((res) => {
								this.editLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['editForm'].resetFields();
								this.editFormVisible = false;
								this.getBrands();
							});
						});
					}
				});
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
						    this.addLoading = true;
						    //es6 Object.assign方法用作对象属性的拷贝，返回结果对象
							let para = Object.assign({}, this.addForm);
							//商品类型是一个数组，获取最后一个值重新赋值
							let productTypeId = para.productTypeId[para.productTypeId.length-1]
							para.productTypeId = productTypeId;
							//处理logoList
                            let logo = para.logoList[0].response.restObj;
                            para.logo = logo;


							this.$http.post("/product/brand/add",para)
								.then(res=>{
								    let {success,message,restObj} = res.data;
								    if(success){
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                        this.$refs['addForm'].resetFields();//重置表单
                                        this.addFormVisible = false;
                                        this.getBrands();
									}else{
                                        this.$message({
                                            message: message,
                                            type: 'error'
                                        });
									}
								})


							/*addUser(para).then((res) => {
								this.addLoading = false;
								//NProgress.done();
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['addForm'].resetFields();
								this.addFormVisible = false;
								this.getBrands();
							});*/
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			    //es6数组的map就是遍历所有元素，返回一个新数组
				var ids = this.sels.map(item => item.id).toString();//8,9
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();

					this.$http.delete("/product/brand/deleteBatch?ids="+ids)
						.then(res=>{
						    let {success,message,restObj} = res.data;
						    if(success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.getBrands();
							}else{
                                this.$message({
                                    message: message,
                                    type: 'error'
                                });
							}
						})

					/*batchRemoveUser(para).then((res) => {
						this.listLoading = false;
						//NProgress.done();
						this.$message({
							message: '删除成功',
							type: 'success'
						});
						this.getBrands();
					});*/
				}).catch(() => {

				});
			}
		},
		mounted() {
			this.getBrands();
			this.loadOptions();
		}
	}

</script>

<style scoped>

</style>